package rules

import (
	"fmt"
	"strings"
)

// RollbackScriptComplianceRule 回滚脚本规范检查规则
type RollbackScriptComplianceRule struct{}

// Name 规则名称
func (r *RollbackScriptComplianceRule) Name() string {
	return "回滚脚本规范检查"
}

// Check 执行检查
func (r *RollbackScriptComplianceRule) Check(data DDLCheckData) CheckResult {
	result := CheckResult{
		Status:  StatusPassed,
		Details: make([]string, 0),
	}

	if strings.TrimSpace(data.RollbackScript) == "" {
		result.Details = append(result.Details, "⚠️ 未提供回滚脚本，跳过回滚脚本规范检查")
		result.Status = StatusSkipped
		return result
	}

	// 检查回滚脚本规范
	upperScript := strings.ToUpper(data.RollbackScript)
	if !strings.Contains(upperScript, "DROP") &&
		!strings.Contains(upperScript, "ALTER") &&
		!strings.Contains(upperScript, "CREATE") {
		result.Details = append(result.Details, "❌ 回滚脚本应包含DROP、ALTER或CREATE语句")
		result.Status = StatusFailed
	} else {
		result.Details = append(result.Details, "✅ 回滚脚本包含有效的SQL操作语句")
	}

	// 检查是否使用schema.table格式
	expectedFormat := fmt.Sprintf("%s.%s", data.Schema, data.Table)
	if strings.Contains(data.RollbackScript, expectedFormat) {
		result.Details = append(result.Details, "✅ 回滚脚本正确使用了schema.table格式")
	} else {
		result.Details = append(result.Details, fmt.Sprintf("❌ 回滚脚本应使用%s格式引用表", expectedFormat))
		result.Status = StatusFailed
	}

	return result
}
